<?php
/**
 * mysql驱动
 *
 * @package util.db.drivers.pdo
 * @since 0.2
 */
class IDbPdoMysql extends IAbstractDbPdo {
	public function connect() {
		parent::connect();
		$charset = $this->config["charset"];
		if ($charset != null) {
			$this->getPdo()->exec("SET NAMES '{$charset}'");
		}
	}
	
	public function getPdoType() {
		return "mysql";
	}
	
	public function getTableList() {
		$stmt = $this->pdo->query("SHOW TABLES");
		return $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
	}
	
	/**
	 * Enter description here...
	 * 
		 $type;
		 $column;
		 $maxLength = 0;
		 $notNull = false;
		 $primaryKey = false;
		 $autoIncrement = false;
		 $binary = false;
		 $unsigned = false;
		 $hasDefault = false;
		 $defaultValue;
	 *
	 * @param unknown_type $name
	 * @return unknown
	 * @see IDarField
	 * @todo 需要添加除TYPE_STR,TYPE_FLOAT等的其他类型
	 */
	public function describeTable($name) {
		$array = $this->fetchAll($this->nativeExec("DESCRIBE `{$name}`"));
		$fields = array();
		foreach ($array as $row) {
			$field = array();
			$field["column"] = $row["Field"];
			$field["notNull"]  = ($row["Null"] == "No")?true:false;
			$field["primaryKey"] = (strtoupper($row["Key"]) == "PRI");
			$field["unsigned"] = preg_match("/unsigned/", $row["Type"]);
			$field["hasDefault"] = ($row["Default"] != null);
			$field["defaultValue"] = $row["Default"];
			$field["autoIncrement"] = ($row["Extra"] == "auto_increment");
			$matches = array();
			 if (preg_match("/^((?:var)?char)\\((\\d+)\\)/", $row["Type"], $matches)) {
                $field["type"] = IDb::TYPE_STR;
                $field["maxLength"] = $matches[2];
            } else if (preg_match("/^decimal\\((\\d+),(\\d+)\\)/", $row["Type"], $matches)) {
                $field["type"] = IDb::TYPE_FLOAT;
                $field["maxLength"] = -1;
            } else if (preg_match("/^((?:small|tiny)?int)\\((\\d+)\\)/", $row["Type"], $matches)) {
                $field["type"] = IDb::TYPE_INT;
       			$field["maxLength"] = -1;	
            } else if (preg_match("/^((?:big|medium)int)\\((\\d+)\\)/", $row["Type"], $matches)) {
            	$field["type"] = IDb::TYPE_LONG;
       			$field["maxLength"] = -1;	
            }
            //其他类型需要添加
            $fields[] = $field;
		}
		return $fields;		
	}	
	
	
	public function limit($sql, $count, $offset = 0) {
		$count = intval($count);
		$offset = intval($offset);
		if ($count < 0) {
			throw new IDbException("sql limit count can not lower than 0");
		}
		if ($offset < 0) {
			throw new IDbException("sql limit offset can not lower than 0");
		}
		if ($count == 0) {
			return $sql;
		}
		return $sql . " LIMIT {$offset},{$count}";
	}
	
	public function quoteKeyword($keyword) {
		return "`" . $keyword . "`";
	}
}


?>